<template>
  <van-nav-bar
    title="注册"
    left-text="返回"
    left-arrow
    @click-left="$router.back()"
  />
  <van-cell-group inset>
    <van-field
      v-model="sms"
      center
      clearable
      label="短信验证码"
      placeholder="请输入短信验证码"
    >
      <template #button>
        <van-button size="small" @click="send" type="primary" :disabled="!show">
          <span v-show="show">发送短信验证码</span>
          <span v-show="!show">{{ btnVal }}s后获取验证码</span>
        </van-button>
      </template>
    </van-field>
  </van-cell-group>

  <van-button
    round
    type="danger"
    @click="submit"
    is-link
    to="/registthree"
    :disabled="sms.length != 5"
    >下一步</van-button
  >
</template>

<script setup lang="ts">
import { ref } from "vue";
import type { Ref } from "vue";
import { showConfirmDialog } from "vant";
import { useRoute, useRouter } from "vue-router";
import { MsgCode } from "@/api/api";

interface IApiCode {
  code: string;
  data: number;
  message: string;
}
let show = ref(true);
let btnVal = ref(60);
const route = useRoute();
const router = useRouter();

const sms: Ref<string> = ref("");

const submit = () => {
  route.query.tel;
  router.push({
    path: "/registtwo",
    query: {
      tel: route.query.tel,
    },
  });
};
const send = () => {
  showConfirmDialog({
    title: "提示",
    message: `将向手机号${route.query.tel}发送短信验证码`,
  }).then(async () => {
    const res = (await MsgCode({
      tel: route.query.tel as string,
    })) as unknown as IApiCode;
    console.log(res);
    console.log(route.query.tel);

    const timer = setInterval(() => {
      if (btnVal.value > 0) {
        btnVal.value--;
        show.value = false;
        console.log();
      } else {
        clearInterval(timer); //清除定时器和复原按钮
        show.value = true;
        btnVal.value = 60;
      }
    }, 1000);
  });
};
</script>

<style lang="scss" scoped>
.van-cell-group {
  margin-top: 4rem;
  margin-bottom: 2.5rem;
}
</style>